package com.cym.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.ModelAndView;
import org.noear.solon.core.handle.UploadedFile;

import com.cym.config.HomeConfig;
import com.cym.model.Function;
import com.cym.model.Project;
import com.cym.model.TestLog;
import com.cym.model.User;
import com.cym.resp.FunctionResp;
import com.cym.resp.TestLogResp;
import com.cym.resp.UserResp;
import com.cym.service.FunctionService;
import com.cym.service.ProjectService;
import com.cym.service.UserService;
import com.cym.sqlhelper.bean.Page;
import com.cym.utils.BaseController;
import com.cym.utils.BeanExtUtil;
import com.cym.utils.JsonResult;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;

@Controller
@Mapping("/adminPage/function")
public class FunctionController extends BaseController {
	@Inject
	FunctionService functionService;
	@Inject
	ProjectService projectService;
	@Inject
	UserService userService;
	@Inject
	HomeConfig homeConfig;

	@Mapping("/upload")
	public Map<String, Object> upload(Context context, UploadedFile upload) throws IOException {
		String url = "/" + DateUtil.format(new Date(), "yyyy-MM") + "/";
		FileUtil.mkdir(homeConfig.file + url);
		url += System.currentTimeMillis() + "." + upload.extension;

		File temp = new File(homeConfig.file + url);
		upload.transferTo(temp);

		Map<String, Object> map = new HashMap<>();
		map.put("uploaded", 1);
		map.put("url", "file" + url);

		return map;
	}

	@Mapping("")
	public ModelAndView index(ModelAndView modelAndView, Page pageReq, //
			String userId, //
			String createUserId, //
			String startTime, //
			String endTime, //
			Integer functionStatus, //
			Integer level, //
			Integer type) {
		Project project = getLoginProject();

		Page<Function> page = functionService.search(pageReq, userId, startTime, endTime, functionStatus, project.getId(), level, type, createUserId);
		Page<FunctionResp> pageResp = BeanExtUtil.copyPageByProperties(page, FunctionResp.class);

		for (FunctionResp functionResp : (List<FunctionResp>) pageResp.getRecords()) {

			functionResp.setUserList(functionService.getUserList(functionResp.getId()));

			List<String> names = new ArrayList<>();
			for (User user : functionResp.getUserList()) {
				names.add(user.getTrueName() + "(" + userService.getTypeName(user.getType()) + ")");
			}
			functionResp.setUserNames(StrUtil.join("&nbsp;&nbsp;", names));
			functionResp.setCreateUser(sqlHelper.findById(functionResp.getCreateUserId(), User.class));

			functionResp.setLevelName(functionService.getLevelName(functionResp.getLevel()));
//			functionResp.setTestStatusName(functionService.getTestStatusName(functionResp.getTestStatus()));
		}

		List<UserResp> list = BeanExtUtil.copyListByProperties(userService.getByProjectId(project.getId()), UserResp.class);
		for (UserResp userResp : list) {
			userResp.setTypeName(userService.getTypeName(userResp.getType()));
		}
		modelAndView.put("userList", list);
		modelAndView.put("createUserId", createUserId);
		modelAndView.put("userId", userId);
		modelAndView.put("level", level);
		modelAndView.put("type", type);

		modelAndView.put("startTime", startTime);
		modelAndView.put("endTime", endTime);
		modelAndView.put("functionStatus", functionStatus);
		String stageName = "";
		// 0：等待阶段。1：开发阶段。2：测试阶段。 5验证阶段 3完成阶段. 4否决阶段
		switch (functionStatus) {
		case 0:
			stageName = "等待阶段";
			break;
		case 1:
			stageName = "开发阶段";
			break;
		case 2:
			stageName = "测试阶段";
			break;
		case 5:
			stageName = "验证阶段";
			break;
		case 3:
			stageName = "完成阶段";
			break;
		case 4:
			stageName = "否决阶段";
			break;
		}
		modelAndView.put("stageName", stageName);
		modelAndView.put("page", pageResp);
		modelAndView.view("/adminPage/function/index.html");
		return modelAndView;
	}

	@Mapping("addOver")

	public JsonResult addOver(Function function, String[] userIds, Integer functionStatus) {
		User user = getLoginUser();

		function.setStatus(functionStatus);
		function.setProjectId(getLoginProject().getId());
		function.setCreateUserId(getLoginUser().getId());
		functionService.insertOrUpdate(function, userIds, user.getId());

		return renderSuccess();
	}

	@Mapping("detail")
	public JsonResult detail(String id) {
		Function function = sqlHelper.findById(id, Function.class);
		FunctionResp functionResp = BeanExtUtil.copyNewByProperties(function, FunctionResp.class);

		functionResp.setUserList(functionService.getUserList(functionResp.getId()));

		List<String> names = functionResp.getUserList().stream().map(User::getName).collect(Collectors.toList());
		functionResp.setUserNames(StrUtil.join("&nbsp;&nbsp;", names));
		functionResp.setCreateUser(sqlHelper.findById(functionResp.getCreateUserId(), User.class));

		List<TestLog> list = functionService.getTestLogList(functionResp.getId());
		List<TestLogResp> rsList = BeanExtUtil.copyListByProperties(list, TestLogResp.class);
		for (TestLogResp testLogResp : rsList) {

			User user = sqlHelper.findById(testLogResp.getUserId(), User.class);
			String typeName = userService.getTypeName(user.getType());
			testLogResp.setDescr(DateUtil.format(new Date(testLogResp.getChangeTime()), "yyyy-MM-dd HH:mm:ss") + " " + user.getTrueName() + "(" + typeName + ")" + "指派给"
					+ userService.getUserNames(testLogResp.getToUserIds()));
		}

		functionResp.setTestLogList(rsList);
		return renderSuccess(functionResp);
	}

	@Mapping("del")

	public JsonResult del(String id) {

		functionService.delete(id);

		return renderSuccess();
	}

	@Mapping("moveOver")

	public JsonResult moveOver(String functionId, Integer status) {

		Function function = sqlHelper.findById(functionId, Function.class);
		if (function.getStatus().equals(status)) {
			return renderError("状态与初始状态相同");
		}

		functionService.move(functionId, status, getLoginUser().getId());

		return renderSuccess();
	}

	@Mapping("testOver")

	public JsonResult testOver(String functionId, Integer testStatus, String[] userIds, String changeMark) {

		functionService.test(functionId, userIds, testStatus, getLoginUser().getId(), changeMark);

		return renderSuccess();
	}
}
